package fractales.servlet;

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JuliaServlet extends HttpServlet
{
	
	private static BufferedImage gradient;
	
	static {
		gradient = new BufferedImage(256, 1, BufferedImage.TYPE_INT_RGB);
		Graphics2D g2d = gradient.createGraphics();
		g2d.setPaint(new GradientPaint(0, 0, new Color(0x333399), 15, 1, Color.YELLOW));
		g2d.fillRect(0, 0, 20, 1);
		g2d.setPaint(new GradientPaint(0, 0, Color.YELLOW, 80, 1, Color.ORANGE));
		g2d.fillRect(20, 0, 150, 1);
		g2d.setPaint(new GradientPaint(0, 0, Color.ORANGE, 5, 1, Color.PINK));
		g2d.fillRect(150, 0, 180, 1);
		g2d.setPaint(new GradientPaint(0, 0, Color.PINK, 50, 1, Color.RED));
		g2d.fillRect(180, 0, 255, 1);
		g2d.setPaint(new GradientPaint(0, 0, Color.RED, 50, 1, Color.BLACK));
		g2d.fillRect(255, 0, 256, 1);
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		response.setContentType("image/jpeg");
		
		int width = 256, height = 256;
		double zoom = 1;
		int rx = 0, ry = 0;
		try {
			String p = request.getParameter("z");
			if (p != null)
				zoom = Double.parseDouble(p);
			p = request.getParameter("x");
			if (p != null)
				rx = Integer.parseInt(p) * width - width;
			p = request.getParameter("y");
			if (p != null)
				ry = Integer.parseInt(p) * height - height;
		}
		catch (NullPointerException e) { }
		
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		
		int m, n;
		double x, y, u, v;
		int i;
		
		double z = zoom * zoom * 150.;
		
//		double x0=0.3, y0=-0.5;
		double x0=-0.5, y0=0.5;
		
		if (z > Double.MAX_VALUE)
			throw new IllegalArgumentException();
		int xmax = rx+width, ymax = ry+height;
		
		double conv = Math.max(x0 * x0  + y0 * y0, 4);
		
		for (n=ry; n<ymax; n++)
		{
			for (m=rx; m<xmax; m++)
			{
				x = m / z;
				y = n / z;
				for (i=0; i<0xff; i++)
				{
					u = x*x - y*y + x0;
					v = 2*x*y + y0;
					if (x*x + y*y > conv)
						break;
					x = u;
					y = v;
                }
   				//int rgb = (i << 16) | (i << 8) | i;
   				int rgb = gradient.getRGB(i, 0);// (i << 16) | (i * 4 << 8) | i * 12;
   				image.setRGB(m-rx, n-ry, rgb);
			}
		}
		
		ServletOutputStream os = response.getOutputStream();
		
		ImageIO.write(image, "png", os);
	}
}